package cn.ee.dfs.wx;

import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Description:
 * Created by TWJ on 2018/7/3 0003 上午 9:33 .
 */
@Component
public class OkHttpUtil {
    private Logger lg = LoggerFactory.getLogger(OkHttpUtil.class);
    @Resource
    private OkHttpClient okHttpClient;

//    public String CONTENT_TYPE_STREAM = "application/octet-stream";

    /**
     * @param url     请求的url
     * @param queries 请求的参数，在浏览器？后面的数据，没有可以传null
     */
    public String get(String url, Map<String, String> queries) {
        StringBuilder sb = new StringBuilder(url);
        if (queries != null && queries.keySet().size() > 0) {
            boolean firstFlag = url.contains("?") ? false : true;
            Iterator iterator = queries.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry entry = (Map.Entry<String, String>) iterator.next();
                if (firstFlag) {
                    sb.append("?").append(entry.getKey()).append("=").append(entry.getValue());
                    firstFlag = false;
                } else {
                    sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
                }
            }
        }
        Request request = new Request
                .Builder()
                .url(sb.toString())
                .build();
        lg.info(" get request url:" + url);
        lg.info(" get request fullUrl:" + sb.toString());
        lg.info(" get request params:" + queries);

        return getResult(request);
    }


    /**
     * POST
     *
     * @param url    请求的url
     * @param params post form 提交的参数
     */
    public String post(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                String value = params.get(key);
                if (StringUtils.isEmpty(value)) value = "";
                builder.add(key, value);
            }
        }
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();

        lg.info(" post request url:" + url);
        lg.info(" post request params:" + params);
        return getResult(request);
    }

    private String getResult(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (status == 200) {
                return response.body().string();
            }
        } catch (Exception e) {
            lg.info("网络 请求  错误..." + e.getMessage());
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

    /**
     * post 上传文件
     *
     * @param fileType 文件类型
     */
    public String postFile(String url, Map<String, Object> params, String fileType) {
        MultipartBody.Builder builder = new MultipartBody.Builder();
        //添加参数
        if (params != null && params.keySet().size() > 0) {
            Set<String> strings = params.keySet();
            for (String key : strings) {
                if (params.get(key) instanceof File) {
                    File file = (File) params.get(key);
                    lg.info("---postFile-----" + file.getName());
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(fileType), file));
                    continue;
                }
                builder.addFormDataPart(key, params.get(key).toString());
            }
        }
        builder.setType(MultipartBody.FORM);//    表单提交类型
        Request request = new Request
                .Builder()
                .url(url)
                .post(builder.build())
                .build();
        lg.info("----------------" + builder.build().toString());
        return getResult(request);
    }
}
